package org.zjx.db;

import org.zjx.common.bean.Room;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RoomDB {
    private static boolean isTableCreated = false;  // Flag to ensure the table is only created once
    private final SQLiteHelper dbHelper;

    public RoomDB() {
        dbHelper = SQLiteHelper.getSingleton();
        // Only create the table once when the instance is first created
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    // Create table for Room
    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS room (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    name TEXT NOT NULL,\n"
                + "    screenId INTEGER NOT NULL,\n"
                + "    follow INTEGER NOT NULL\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    // Insert a Room record
    public void insert(Room room) {
        String sql = "INSERT INTO room(name, screenId, follow) VALUES(?, ?, ?)";
        Object[] params = {
                room.getName(),
                room.getScreenId(),
                room.isFollow() ? 1 : 0  // Assuming follow is a boolean, converting it to integer
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Update a Room record
    public void update(Room room) {
        String sql = "UPDATE room SET name = ?, screenId = ?, follow = ? WHERE id = ?";
        Object[] params = {
                room.getName(),
                room.getScreenId(),
                room.isFollow() ? 1 : 0,  // Assuming follow is a boolean, converting it to integer
                room.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Delete a Room record by ID
    public void deleteById(int id) {
        String sql = "DELETE FROM room WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    // Find Room by ID
    public Room findById(int id) {
        String sql = "SELECT * FROM room WHERE id = ?";
        Object[] params = {id};
        List<Room> rooms = dbHelper.executeQuery(sql, params, Room.class);
        if (rooms.isEmpty()) return null;
        return rooms.get(0);
    }

    public Room findByName(String name) {
        String sql = "SELECT * FROM room WHERE name = ?";
        Object[] params = {name};
        List<Room> rooms = dbHelper.executeQuery(sql, params, Room.class);
        if (rooms.isEmpty()) return null;
        return rooms.get(0);
    }



    // Get all rooms
    public List<Room> findAll() {
        String sql = "SELECT * FROM room";
        Object[] params = {};
        return dbHelper.executeQuery(sql, params, Room.class);
    }

    // Paginated query for Rooms
    public Map<String, Object> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        String sql = "SELECT * FROM room LIMIT ? OFFSET ?";
        Object[] params = {pageSize, offset};
        List<Room> rooms = dbHelper.executeQuery(sql, params, Room.class);

        String countSql = "SELECT COUNT(*) FROM room";
        Object[] countParams = {};
        List<Integer> totalRecordsList = dbHelper.executeQuery(countSql, countParams, Integer.class);
        int totalRecords = totalRecordsList.isEmpty() ? 0 : totalRecordsList.get(0);

        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("roomList", rooms);
        result.put("totalRecords", totalRecords);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);

        return result;
    }

    // Clear all Room data
    public void clearData() {
        dbHelper.clearData("room");
    }

    // Drop the Room table
    public void dropTable() {
        dbHelper.dropTable("room");
    }
}
